package com.shirotest.shiro_test.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * @Author: 秃头不用洗发水
 * @Date: 2021-03-21
 * @Description:
 */
@Controller
public class MyController {
    @RequestMapping({"/","/index"})
    public String toIndex(Model model){
        model.addAttribute("msg","shiro_Test:这是index");
        return "index";
    }
    @RequestMapping("/user/add")
    public String toadd(){
        return "add";
    }

    @RequestMapping("/user/delete")
    public String todelete(){
        return "delete";
    }
    //登录
    @RequestMapping("login")
    public String tologin(){
        return "login";
    }

        @RequestMapping("/log")
        public String log (String username , String password ,Model model){
            //获取当前用户subject
            Subject subject = SecurityUtils.getSubject();

            //封装用户的登录数据(username,password-->token)
            UsernamePasswordToken token = new UsernamePasswordToken(username,password);

            //登录令牌-->判断权限、角色 , 执行登录方法 ，无异常登录成功 （捕获一下）
            try{
                subject.login(token); //执行登录方法
                return "index";
            } catch (UnknownAccountException e) { //用户名错误
                model.addAttribute("msg","用户名错误");
                return "login";
            }catch (IncorrectCredentialsException e){
                model.addAttribute("msg","密码错误");
                return "login";
            }

    }
}
